package com.hm.pan.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.hm.pan.annotation.CheckLogin;
import com.hm.pan.model.FileInfo;
import com.hm.pan.model.ResultObj;
import com.hm.pan.model.User;
import com.hm.pan.model.UserFile;
import com.hm.pan.service.FileUploadService;
import com.hm.pan.service.UserFileService;

@RestController
@RequestMapping("md5")
@CheckLogin
public class FileUploadController {

	@Resource
	private FileUploadService fileUploadService;
	@Resource
	private UserFileService userFileService;

	// 通过MD5查找文件信息，如果有的话，就不用上传文件，只要向用户文件里插入文件信息就行
	@RequestMapping("findyes")
	public Object findMd5(String md5, Timestamp uploadTime, String fileName, String caozuoPath, HttpSession session)
			throws Exception {
		UserFile oneFileByPath2 = userFileService.getOneFileByPath(caozuoPath);// 通过前端传过来的操作路径找到该用户文件对象
		Long fatherId2 = oneFileByPath2.getUserfileId();
//		System.out.println("================"+md5);
		User user = (User) session.getAttribute("user"); // 通过session拿到前端用户信息
//		System.out.println("-----------------"+user);
		Long userId = user.getUserId(); // 获取前端传过来的用户id
//		System.out.println("+++++++++++++++++"+userId);

		String newName = getName(fileName);

		Object filemd5 = fileUploadService.findMd5(md5);
		// 如果数据里有MD5，就不用上传，但是用户文件需要插入。
		if (filemd5 != null) {
			Object fileInfo = fileUploadService.findByNameFatherId(fileName, fatherId2);
			if (fileInfo != null) {
				fileUploadService.insertUserFile(uploadTime, newName, md5, fatherId2, userId);
			} else {
				fileUploadService.insertUserFile(uploadTime, fileName, md5, fatherId2, userId);
			}
			return new ResultObj(200, fileInfo);
		} else {
			return new ResultObj(400, filemd5);
		}

	}

	// 如果前面的MD5没有找到文件信息的话，就会返回一个400到前端，前端再根据判断，把文件给上传。
	@RequestMapping("findnot")
	public Object aa(@RequestParam("file") MultipartFile file, String md5, Long fileSize, String fileName,
			Timestamp uploadTime, String caozuoPath, HttpSession session, HttpServletRequest req) throws Exception {

		String newName = getName(fileName);

		// 将文件存到指定项目文件下，没有的话就创建
//		File realpath = ResourceUtils.getFile("");
//		String realpath = req.getServletContext().getRealPath("/upload");
		// String filePath = realpath+fileName;
		File dest = new File("upload");
		File file2 = new File(dest, newName);
		// 检测是否存在该目录
		if (!dest.exists()) {
			dest.mkdirs();
		}
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(file2);
			fos.write(file.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println("<<<<<<<<<<<<<<<< "+file2.getAbsolutePath());
		FileInfo fileInfo = new FileInfo();
		fileInfo.setFilePath(file2.getPath()); // 获取文件的相对路径
		fileInfo.setFileMd5(md5);
		fileInfo.setFileSize(fileSize);

		User user = (User) session.getAttribute("user"); // 通过session拿到前端用户信息
//		System.out.println("-----------------"+user);
		Long userId = user.getUserId(); // 获取前端传过来的用户id
//		System.out.println("+++++++++++++++++"+userId);
		Object fileinfo = fileUploadService.insertFileInfo(fileInfo);

		UserFile oneFileByPath = userFileService.getOneFileByPath(caozuoPath); // 通过操作路径找到fatherId

		if (oneFileByPath != null && fileinfo != null) {
			Long fatherId = oneFileByPath.getUserfileId();
			Object findByName = fileUploadService.findByNameFatherId(fileName, fatherId);
			if (findByName != null) {
				fileUploadService.insertUserFile(uploadTime, newName, md5, fatherId, userId);
			} else {
				fileUploadService.insertUserFile(uploadTime, fileName, md5, fatherId, userId);
			}
			return new ResultObj(200, fileinfo);
		}

		return new ResultObj(400, fileinfo);
	}

	// 获取不同的文件名
	public String getName(String fileName) {
		// 解决文件名重名，以时间戳+随机数
		// 获得当前时间

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		// 转换为字符串
		String formDate = format.format(new Date());
		// 随机生成文件编号
		int random = new Random().nextInt(1000);
		String[] split = fileName.split("\\.");

		// 1.2.3.4.cc
		// mm
		StringBuffer sb = new StringBuffer(split[0]);
		for (int i = 1; i < split.length - 1; i++) {
			sb.append('.').append(split[i]);
		}

		sb.append('_').append(formDate).append(random);

		if (fileName.indexOf(".") != -1) {
			sb.append('.').append(split[split.length - 1]);
		}

		String name = sb.toString();

		return name;
	}

}
